package com.hopedove.yieldmanage.activity;

import static org.koin.java.KoinJavaComponent.inject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.repository.CommonRepository;
import com.hopedove.utils.CommonUtil;
import com.hopedove.utils.ParseUtils;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.SimpleDialog;
import com.hopedove.yieldmanage.R;
import com.hopedove.yieldmanage.domain.net.SelectDict;
import com.hopedove.yieldmanage.domain.net.YieldLogin;
import com.hopedove.yieldmanage.entity.SpinnerEntity;
import com.hopedove.yieldmanage.entity.UserBean;
import com.hopedove.yieldmanage.utils.SharedPreUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import kotlin.Lazy;

/**
 * 织造产量管理系统/登录
 */
public class YieldLoginActivity extends BaseActivity implements OnClickListener {

    Lazy<CommonRepository> repository = inject(CommonRepository.class);

    private Button loginBtn;
    private EditText accountEt;
    private EditText passwordEt;
    private Spinner mBmmcSp;
    private TextView versionTv;
    //车间下拉框适配器
    private ArrayAdapter<String> mBmmcSpAdapter;
    //记录存储车间的text值
    private List<String> mBmmcList = new ArrayList<>();
    //记录车间数据字典
    List<SpinnerEntity> mSpinnerList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yield_login_activity);
        initDate();
        initView();
        initEvent();
        selectDict();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次页面到前台都更新服务器时间
        repository.getValue().getServerDateTime(true);
    }

    private void initDate() {
        mSpinnerList.add(new SpinnerEntity("请选择车间", ""));
    }

    private void initView() {
        loginBtn = findViewById(R.id.login_loginBtn);
        accountEt = findViewById(R.id.login_accountEt);
        passwordEt = findViewById(R.id.login_passwordEt);
        versionTv = findViewById(R.id.versionTv);
        mBmmcSp = findViewById(R.id.login_bmmcSp);
        // 设置车间下拉框适配器 数据来源于访问服务器的数据字典
        mBmmcSpAdapter = new ArrayAdapter<>(this, R.layout.yield_spinner_item, mBmmcList);
        mBmmcSpAdapter.setDropDownViewResource(R.layout.yield_spinner_drop_item);
        mBmmcSp.setAdapter(mBmmcSpAdapter);

        accountEt.setFocusable(true);
        accountEt.setFocusableInTouchMode(true);

        accountEt.requestFocus();
        accountEt.requestFocusFromTouch();
        accountEt.findFocus();
        versionTv.setText("当前版本：V" + CommonUtil.getAppVersionName(this));
    }


    private void initEvent() {
        loginBtn.setOnClickListener(this);
        accountEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                startLoginByScan();
            }
            return false;
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.login_loginBtn) {
            startLogin();
        }
    }

    /**
     * 通过扫描的方式登陆
     */
    private void startLoginByScan() {

        String account = accountEt.getText().toString().trim();

        String password = CommonUtil.MD5(passwordEt.getText().toString().trim());

        if (TextUtils.isEmpty(password)) {
            password = CommonUtil.MD5("abc123");
        }

        String bmmc = "";
        //车间不是必选项
        int position = mBmmcSp.getSelectedItemPosition();
        if (position < 0) {
            SimpleDialog.show(this, "登录失败，服务器连接异常！");
            return;
        }
        bmmc = mSpinnerList.get(position).fieldValue;

        if (TextUtils.isEmpty(account)) {
            ToastUtil.longToast(getBaseContext(), "请输入工号！");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.longToast(getBaseContext(), "请输入密码！");
            return;
        }
        login(account, password, bmmc);
    }

    /**
     * 开始登陆，正常手动输入
     */
    private void startLogin() {
        String account = accountEt.getText().toString().trim();

        String password = CommonUtil.MD5(passwordEt.getText().toString().trim());
        String bmmc = "";
        //车间不是必选项
        int position = mBmmcSp.getSelectedItemPosition();
        if (position < 0) {
            SimpleDialog.show(this, "登录失败，服务器连接异常！");
            return;
        }
        bmmc = mSpinnerList.get(position).fieldValue;

        if (TextUtils.isEmpty(account)) {
            ToastUtil.longToast(getBaseContext(), "请输入工号！");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.longToast(getBaseContext(), "请输入密码！");
            return;
        }
        login(account, password, bmmc);
    }

    /**
     * 登录
     */
    private void login(String account, String password, String bmmc) {
        showWait();

        YieldLogin yieldLogin = new YieldLogin(account, password, bmmc);
        Communication.asyncRequest(yieldLogin, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    String opt;
                    String msg;

                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    opt = jsonObj.optString("OPT_FLAG");
                    msg = jsonObj.optString("MSG_INFO");
                    if ("SUCCESS".equals(opt)) {

                        JSONObject userBeanObj = jsonObj.optJSONObject("userBean");
                        // 保存 userBean 数据到本地，格式为json字符串
                        SharedPreUtil.putValue(this, SharedPreUtil.USERBEAN, userBeanObj.toString());

                        UserBean userBean = new UserBean();
                        userBean = ParseUtils.parse(userBeanObj.toString(), UserBean.class);


                        // 保存权限代码
                        JSONArray QXCOMMArray = jsonObj.optJSONArray("QXCOMM");
                        // 闲置空
                        SharedPreUtil.putValue(this, SharedPreUtil.CM0140202, "");
                        for (int i = 0; i < QXCOMMArray.length(); i++) {
                            JSONObject QXCOMMObj = QXCOMMArray.getJSONObject(i);
                            String CM0140202 = QXCOMMObj.optString("CM0140202");
                            if (!TextUtils.isEmpty(CM0140202)) {
                                SharedPreUtil.putValue(this, SharedPreUtil.CM0140202, CM0140202);
                                break;
                            }
                        }

                        String YHM = userBean.XTYHBean.YHM;
                        String BMJC = userBean.XTYHBean.BMJC;
                        SharedPreUtil.putValue(this, SharedPreUtil.YHMC, YHM);


                        if (YHM.contains(BMJC)) {
                            YHM = YHM.substring(BMJC.length());
                        }
                        //改为从文本框中获取用户id
                        //去掉所有字母  2017年12月15日修改
                        //String YHM =accountEt.getText().toString().trim().replaceAll("[a-zA-Z]","");
                        // 保存YHM 员工工号
                        SharedPreUtil.putValue(this, SharedPreUtil.YHM, YHM);
                        /**********************2017年12月2日，更改bmmc保存数据来源*******************/
                        String userBmmc = userBean.XTYHBean.BMMC;
                        SharedPreUtil.putValue(this, SharedPreUtil.BMMC, userBmmc);
                        /*************************结束*********************************/

                        Intent intent = new Intent(this, YieldMainActivity.class);
                        startActivity(intent);
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            SimpleDialog.show(this, "登陆失败");
                        } else {
                            SimpleDialog.show(this, msg);
                        }
                    }

                } catch (Exception e) {
                    ToastUtil.longToast(getBaseContext(), "数据异常");
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, "登陆失败，请检查用户名和密码是否正确！");
            }
        });
    }

    /**
     * 获取车间下拉框值
     */
    private void selectDict() {
        showWait();

        SelectDict selectDict = SelectDict.newWorkshop();
        Communication.asyncRequest(selectDict, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    Gson gson = new Gson();
                    List<SpinnerEntity> spinnerList = gson.fromJson(((OkResponse) r).getData(), new TypeToken<List<SpinnerEntity>>() {
                    }.getType());
                    //保存到spinner数据字典中
                    mSpinnerList.addAll(spinnerList);
                    //保存车间文本值，适配下拉框
                    for (SpinnerEntity spinnerEntity : mSpinnerList) {
                        mBmmcList.add(spinnerEntity.fieldText);
                    }
                    //下拉框数据刷新
                    mBmmcSpAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

}
